package com.cloudcc.migrationToNewSys;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudcc.ccTool.CCObject;
import com.cloudcc.ccTool.CCService;
import com.cloudcc.ccTool.StringUtil;
import com.cloudcc.ccTool.UserInfo;
import java.util.*;

import static java.lang.Thread.sleep;


public class FieldMigration {
    private CCService cs;
    private UserInfo userInfo;
    private MigrationCCService mcs;

    public FieldMigration(UserInfo userInfo) {
        this.userInfo = userInfo;
        cs = new CCService(userInfo);
        mcs = new MigrationCCService();
    }

    public String path;//标准接口地址

    public static void main(String[] args) throws Exception {
        new FieldMigration(new UserInfo()).Execute();
    }

    public Map allObject() {
        Set<String> data = new HashSet<>();
        data.add("u8ckda");

        // 初始化一个映射，用于存储对象名称与ID的对应关系
        Map<String, String> tableMap = new HashMap();
        // 构造查询语句，以获取对象的详细信息
        String objsql = "select datatable_name,schemetable_name,prefix,id,label from TP_SYS_OBJECT where schemetable_name in " + StringUtil.set2SqlIn(data) + "";
        // 执行查询并获取结果列表
        List<CCObject> dlist = cs.cqlQuery("TP_SYS_OBJECT", objsql);
        // 如果查询结果不为空，则遍历结果列表，提取并存储对象名称与ID的对应关系
        if (dlist.size() > 0) {
            for (CCObject ac : dlist) {
                String tablename = StringUtil.str(ac.get("schemetable_name"));
                String tableid = StringUtil.str(ac.get("id"));
                // 将对象名称与ID的对应关系存储在映射中
                tableMap.put(tablename, tableid);
            }
        }
        // 返回包含对象名称与ID映射的Map对象
        return tableMap;
    }

    public void Execute() throws Exception {
        System.out.println("对象迁移开始 =================== ");
        Map<String, String> tableMap = allObject();
        if (!tableMap.isEmpty()) {
            tableMap.forEach((key, value) -> {
                if (!"".equals(value)) {//系统里面有这个值
                    try {
                        creatObject(key);//返回创建的id和api
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.out.println("未查询到" + key);
                    return;
                }
            });
            System.out.println("对象迁移结束 =================== ");
            System.out.println("字段迁移开始 =================== ");
            tableMap.forEach((key, value) -> {
                if (!"".equals(value)) {//系统里面有这个值
                    try {
                        insertcco(key, value);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.out.println("未查询到" + key);
                    return;
                }
            });
            System.out.println("字段迁移结束 =================== ");
            System.out.println("按钮迁移开始 =================== ");
            tableMap.forEach((key, value) -> {
                if (!"".equals(value)) {//系统里面有这个值
                    try {
                        buttonExecute(key);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    System.out.println("未查询到" + key);
                    return;
                }
            });
            System.out.println("按钮迁移结束 =================== ");


        }

    }

    public JSONObject creatObject(String apiname) throws Exception {
        String sql = String.format("select isquickcreated,isreportcreated,show_format,schemetable_name,label,data_type,begin_index,islbs,(select name from  TP_SYS_SCHEMETABLE  where SCHEMETABLE_ID  = TP_SYS_OBJECT.id  and schemefield_name='name') namelabel from TP_SYS_OBJECT where schemetable_name='%s'", apiname);
        List<CCObject> ccObjects = cs.cqlQuery("tp_sys_object", sql);
        JSONObject ccobject = new JSONObject();
        if (!ccObjects.isEmpty()) {
            ccobject.put("isquickcreated", ccObjects.get(0).get("isquickcreated") == null ? "" : ccObjects.get(0).get("isquickcreated").toString());
            ccobject.put("isreportcreated", ccObjects.get(0).get("isreportcreated") == null ? "" : ccObjects.get(0).get("isreportcreated").toString());
            ccobject.put("showFormat", ccObjects.get(0).get("show_format") == null ? "{yyyy}{mm}{dd}{000}" : ccObjects.get(0).get("show_format").toString());
            ccobject.put("objectapiname", ccObjects.get(0).get("schemetable_name") == null ? "" : ccObjects.get(0).get("schemetable_name").toString());
            ccobject.put("label", ccObjects.get(0).get("label") == null ? "" : ccObjects.get(0).get("label").toString());
            ccobject.put("dataType", ccObjects.get(0).get("data_type") == null ? "" : ccObjects.get(0).get("data_type").toString());
            ccobject.put("beginIndex", ccObjects.get(0).get("begin_index") == null ? "0" : ccObjects.get(0).get("begin_index").toString());
            ccobject.put("islbs", ccObjects.get(0).get("islbs") == null ? "" : ccObjects.get(0).get("islbs").toString());
            ccobject.put("nameLabel", ccObjects.get(0).get("namelabel") == null ? "" : ccObjects.get(0).get("namelabel").toString());
        }
        JSONObject creatObjectpar = new JSONObject();//创建对象参数
        creatObjectpar.put("iscreatperm", "true");
        creatObjectpar.put("profileFieldArr", createProfileObjectJson());
        JSONObject objJson = new JSONObject();
        String objectapiname = ccobject.getString("objectapiname");
        String nameLabel = ccobject.getString("nameLabel");
        creatObjectpar.put("nameLabel", nameLabel);
        ccobject.put("schemetableName", objectapiname);
        ccobject.remove("objectapiname");
        ccobject.remove("nameLabel");
        creatObjectpar.put("obj", ccobject);
        objJson.put("objname", objectapiname);
        String objectCheckSql = String.format("select id from tp_sys_object where schemetable_Name='%s'", objectapiname);
        List<CCObject> objectCheck = mcs.cqlQuery("tp_sys_object", objectCheckSql);
        String objectid = "";
        if (!objectCheck.isEmpty()) {
            objectid = objectCheck.get(0).get("id").toString();
            objJson.put("objid", objectid);
            System.out.println("对象api名称:"+objectapiname+"'" + objectapiname + "'已存在，请更改api名称");
        } else {
//            System.out.println(" creatObjectpar.toJSONString() = " + creatObjectpar.toJSONString());
            String response = mcs.CCPost(mcs.gatewayUrl() + "/setup/api/customObject/saveButton", creatObjectpar.toString());
            JSONObject resp = JSONObject.parseObject(response);
            if (resp.getString("result").equals("true")) {
                objectid = resp.getJSONObject("data").getString("id");
                System.out.println("对象" + nameLabel+"("+objectapiname+")创建成功，新建对象id为："+objectid);
            }else {
                System.out.println("对象" + nameLabel+"("+objectapiname+")创建失败，"+resp.getString("returnInfo"));
            }
            objJson.put("objid", objectid);
        }
        return objJson;
    }


    public void insertcco(String apiname, String apiid) throws Exception {
        String sql = "SELECT t1.schemefield_length," +
                " t1.decimal_places," +
                " t1.id fieldid," +
                " t1.schemefield_name," +
                " t1.expression," +
                " t1.expression_type," +
                " t1.schemefield_type AS schemefield_type_desc," +
                "  CASE WHEN t1.schemefield_type = 'A' THEN '富文本' WHEN t1.schemefield_type = 'S' THEN '文本' WHEN t1.schemefield_type = 'D' THEN '日期' WHEN t1.schemefield_type = 'F' THEN '日期/时间' WHEN t1.schemefield_type = 'V' THEN '自动编号' WHEN t1.schemefield_type = 'N' THEN '数字' WHEN t1.schemefield_type = 'Y' THEN '查找关系' WHEN t1.schemefield_type = 'L' THEN '选项列表' WHEN t1.schemefield_type IN ('ct', 'c', 'C') THEN '币种' WHEN t1.schemefield_type = 'X' THEN '文本区' WHEN t1.schemefield_type = 'U' THEN 'URL' WHEN t1.schemefield_type = 'R' THEN '记录类型' WHEN t1.schemefield_type = 'FL' THEN '文件' WHEN t1.schemefield_type = 'E' THEN '邮箱' WHEN t1.schemefield_type = 'Z' THEN '公式' WHEN t1.schemefield_type = 'B' THEN '复选框' WHEN t1.schemefield_type = 'H' THEN '电话' WHEN t1.schemefield_type = 'J' THEN '文本区（长）' WHEN t1.schemefield_type = 'MR' THEN '查找多选' WHEN t1.schemefield_type = 'LT' THEN '地理定位' WHEN t1.schemefield_type = 'AD' THEN '地址' WHEN t1.schemefield_type = 'P' THEN '百分比' WHEN t1.schemefield_type = 'IMG' THEN '图片' WHEN t1.schemefield_type = 'M' THEN '主详信息关系' ELSE t1.schemefield_type END AS schemefield_type_label," +
                " ( SELECT GROUP_CONCAT(codeValue ORDER BY sortorder SEPARATOR '/') FROM tp_sys_code WHERE codetype = t1.id AND render = -1 ) ptext," +
                " ( SELECT GROUP_CONCAT(isdefaultvalue ORDER BY sortorder SEPARATOR '/') FROM tp_sys_code WHERE codetype = t1.id AND render = -1 ) ptextvalue," +
                " t2.label_name," +
                " ( select schemetable_name from TP_SYS_OBJECT where id = t1.lookup_obj ) as lookup_api," +
                " ( select label from TP_SYS_OBJECT where id = t1.SCHEMETABLE_ID ) objname" +
                " FROM TP_SYS_SCHEMETABLE t1 JOIN tp_sys_multi_lang t2 ON t2.relation_id = t1.id AND t2.type = 'field' AND t2.country = 'zh' " +
                " WHERE  t1.SCHEMETABLE_ID  = '" + apiid + "'  and iscustom = 1 " +
                " ORDER BY t1.schemefield_type, CASE WHEN t1.schemefield_name IN ('id', 'name') THEN 1 ELSE 0 END, t1.iscustom, t1.createdate, t1.schemefield_name";
        List<CCObject> cco = cs.cqlQuery("TP_SYS_OBJECT", sql);
        List<CCObject> objcco = mcs.cqlQuery("TP_SYS_OBJECT",
                "select id from TP_SYS_OBJECT where schemetable_name='" + apiname + "'");
        System.out.println("objcco = " + sql);
        if (cco.isEmpty()) {
            System.out.println("未查找到需要迁移的对象");
            return;
        }
        if (objcco.isEmpty()) {
            System.out.println("未找到对象" + apiname);
            return;
        }
        String objid = objcco.get(0).get("id").toString();
        if (cco.isEmpty()) {
            System.out.println("未找到对象" + apiname);
            return;
        }
        for (CCObject row : cco) {



            String bq = row.get("label_name") == null ? "" : row.get("label_name").toString();
            String api = row.get("schemefield_name") == null ? "" : row.get("schemefield_name").toString();
            String fieldid = row.get("fieldid") == null ? "" : row.get("fieldid").toString();
            String objSql = String.format("select id from  TP_SYS_SCHEMETABLE where schemetable_id='%s' and schemefield_name='%s'", objid, api);
            List<CCObject> ccObjects = mcs.cqlQuery("TP_SYS_SCHEMETABLE", objSql);
            if (!ccObjects.isEmpty()) {
                System.out.println(String.format("对象'%s'下已存在字段:%s'%s'", apiname,bq, api));
                continue;
            }
            sleep(6000);// 休眠10秒
            String lx = row.get("schemefield_type_desc") == null ? "" : row.get("schemefield_type_desc").toString();
            String type = row.get("schemefield_type_label") == null ? "" : row.get("schemefield_type_label").toString();
            String lxx = lx + ":" + type;
            JSONObject ret = new JSONObject();
            ret.put("objid", objid);
            ret.put("dtype", lxx);
            ret.put("fdtype", lx);
            if (!lx.equals("Z") && !lx.equals("V")) {
                ret.put("ischecked", "false");
                ret.put("iscover", "");
                ret.put("ischecked", row.get("expression_type") == null ? "" : row.get("expression_type").toString());
                ret.put("iscover", row.get("expression_type") == null ? "" : row.get("expression_type").toString());
            }
            ret.put("formulaText", row.get("expression") == null ? "" : row.get("expression").toString());
            try {
                handleSpecialTypes(row, lx, fieldid, ret);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            handleFormulaType(row, lx, ret);
            ret.put("layoutIds", "");
            JSONObject obj = null;
            try {
                obj = createObjectJson(bq, api, lx, row);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (obj == null) {
                continue;
            }
            ret.put("obj", obj);
            JSONArray objects = null;
            try {
                objects = createProfileFieldJson(lx, api, apiname);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            ret.put("profileFieldJson", objects);
//                System.out.println("ret = " + ret);
            String response = mcs.CCPost(mcs.gatewayUrl() + "/setup/api/fieldSetup/save", ret.toJSONString());
            JSONObject reto = JSONObject.parseObject(response);
            if (reto.get("result").toString().equals("true")) {
                if (lx.equals("Y") || lx.equals("M") || lx.equals("MR")) {
                    lookupFilterExecute(api, apiname);
                }
                System.out.println("字段："+bq+"("+api+")创建成功，字段id:"+reto.get("data"));
            }else {
                System.out.println("字段："+bq+"("+api+")创建失败，原因："+reto.get("returnInfo"));
            }
        }

    }

    private void handleSpecialTypes(CCObject row, String lx, String fieldid, JSONObject ret) throws Exception {
        if ("L".equals(lx) || "Q".equals(lx)) {
            String val = "";
            String lbz = row.get("ptext") == null ? "" : row.get("ptext").toString();
            String isdefval = row.get("ptextvalue") == null ? "" : row.get("ptextvalue").toString();
            String[] del = isdefval.split("/");
            boolean contains = Arrays.stream(del).anyMatch("1"::equals);
            String[] split = lbz.split("/");
            for (String s : split) {
                val += s + "\r\n";
            }
            ret.put("useGlobalSelect", "0");
            ret.put("globalSelectId", "province");
            ret.put("ptext", val);
            ret.put("isPicklistSorted", "0");
            if (contains) {
                ret.put("defPl", "1");
            } else {
                ret.put("defPl", "0");
            }
        } else if ("encd".equals(lx)) {
            ret.put("masktype", "all");
            ret.put("maskcharacter", "*");
            ret.put("encrypttype", "{AAAA}{****}{AAAA}");
        } else if ("V".equals(lx)) {
            List<CCObject> autonum = cs.cqlQuery("tp_sys_autonum", String.format("select show_format,begin_index from tp_sys_autonum where related_fieldid='%s'", fieldid));
            if (!autonum.isEmpty()) {
                ret.put("showFormat", autonum.get(0).get("show_format"));
                ret.put("beginIndex", autonum.get(0).get("begin_index"));
            } else {
                ret.put("showFormat", "{yyyy}{mm}{dd}{000}");
                ret.put("beginIndex", "0");
            }
        }
    }


    private void handleFormulaType(CCObject row, String lx, JSONObject ret) {
        if ("Z".equals(lx)) {
            if ("Z".equals(lx)) {
                ret.put("formulaType", row.get("expression_type") == null ? "" : row.get("expression_type").toString());
            }
        }
    }

    private JSONObject createObjectJson(String bq, String api, String lx, CCObject row) throws Exception {
        JSONObject obj = new JSONObject();
        obj.put("id", "");
        obj.put("nameLabel", bq);
        obj.put("apiname", api);
        obj.put("remark", "");
        obj.put("helps", "");
        if ("Y".equals(lx) || "M".equals(lx) || "MR".equals(lx)) {
            String lookupObj = row.get("lookup_api") == null ? "" : row.get("lookup_api").toString();
            //判断首字母是否大写，创建一个新的字符串  如果大写改成小写，如果小写改成大写
            String first = lookupObj.substring(0, 1);
            String lookupObj_new = "";
            if (first.equals(first.toUpperCase())) {
                lookupObj_new = first.toLowerCase() + lookupObj.substring(1, lookupObj.length());
            } else {
                lookupObj_new = first.toUpperCase() + lookupObj.substring(1, lookupObj.length());
            }
            String objid_sql = "select id from TP_SYS_OBJECT where schemetable_name='" + lookupObj + "' or schemetable_name='" + lookupObj_new + "'";
            List<CCObject> tpSysObject = mcs.cqlQuery("TP_SYS_OBJECT", objid_sql);
            if (!tpSysObject.isEmpty()) {
                obj.put("lookupObj", tpSysObject.get(0).get("id").toString());
            } else {
                System.out.println(bq + "未找到");
                return null;
            }
            if (!"MR".equals(lx)) {
                obj.put("childrelationName", row.get("objname") == null ? "" : row.get("objname").toString());
                obj.put("defaultValue", "");
            }

            if ("Y".equals(lx)) {
                obj.put("lookupObjDefaultField", "--无--");
            }
            if ("M".equals(lx)) {
                obj.put("mainlayoutIds", "");
            }
        }
        String schemefieldLength = row.get("schemefield_length") == null ? "" : row.get("schemefield_length").toString();
        if ("".equals(schemefieldLength) || schemefieldLength == null) {
            schemefieldLength = "255";
        }
        obj.put("schemefieldLength", schemefieldLength);
        if ("N".equals(lx) || "c".equals(lx) || "P".equals(lx) || "Z".equals(lx)) {//带小数位
            if ("N".equals(lx)) {
                obj.put("isrepeat", "true");
                obj.put("displayThousands", "0");
            }
            String decimalPlaces = row.get("decimal_places") == null ? "" : row.get("decimal_places").toString();
            if ("".equals(decimalPlaces) || decimalPlaces == null) {
                decimalPlaces = "2";
            }
            if ("".equals(schemefieldLength) || schemefieldLength == null) {
                schemefieldLength = "10";
            }
            obj.put("schemefieldLength", schemefieldLength);
            obj.put("decimalPlaces", decimalPlaces);
        }
        if ("S".equals(lx)) {
            obj.put("isrepeat", "true");
            obj.put("casesensitive", "");
            obj.put("placeholder", "");
        }
        if ("F".equals(lx)) {
            obj.put("defaultValue", "");
            obj.put("isrepeat", "3");
        }
        if ("L".equals(lx)) {
            obj.put("edittype", "select");
        }

        if ("Q".equals(lx)) {
            obj.put("visibleLines", "4");
            obj.put("showalloptions", "0");
            obj.put("renderstyle", "1");
        }

        return obj;
    }

    /**
     * TODO 查询简档给新字段赋值
     *
     * @param lx
     * @param fieldapi
     * @return
     * @throws Exception
     */
    private JSONArray createProfileFieldJson(String lx, String fieldapi, String apiname) throws Exception {
        JSONArray objects = new JSONArray();
        String profileSql = "select ( select profilename from tp_sys_profile where id = tp_sys_profile_field.profile_id ) profilename," +
                " case visible when 0 then 'false' when 1 then 'true' else '' end visible," +
                " case readonly when 0 then 'false' when 1 then 'true' else '' end readonly," +
                " profile_id from tp_sys_profile_field" +
                " where (select apiname from tp_sys_schemetable where id=tp_sys_profile_field.field_id ) ='" + fieldapi + "'" +
                " and (select schemetable_name from TP_SYS_OBJECT where id=tp_sys_profile_field.obj_id )='" + apiname + "'";
        List<CCObject> profiles = cs.cqlQuery("TP_SYS_PROFILE", profileSql);
        for (CCObject proCCO : profiles) {
            JSONObject profile = new JSONObject();
            String profilename = proCCO.get("profilename") == null ? "" : proCCO.get("profilename").toString();
            List<CCObject> profileCCO = mcs.cqlQuery("tp_sys_profile", "select id from tp_sys_profile where profilename='" + profilename + "'");
            if (profileCCO.isEmpty()) {
                continue;
            }
            profile.put("profileId", profileCCO.get(0).get("id").toString());
            profile.put("visible", proCCO.get("visible") == null ? "" : proCCO.get("visible").toString());
            profile.put("readonly", proCCO.get("readonly") == null ? "" : proCCO.get("readonly").toString());
            if ("encd".equals(lx)) {
                profile.put("encryptvisible", "false");
            }
            objects.add(profile);
        }
        return objects;
    }

    private JSONArray createProfileObjectJson() {
        JSONArray objects = new JSONArray();
        List<CCObject> profiles = mcs.cqlQuery("TP_SYS_PROFILE", "select id from tp_sys_profile");
        for (CCObject proCCO : profiles) {
            JSONObject profile = new JSONObject();
            profile.put("profileid", proCCO.get("id").toString());
            if (proCCO.get("id").toString().equals("aaa000001")) {
                profile.put("permission", "1,1,1,1,1,1");
            } else {
                profile.put("permission", "1,1,1,1,1,0");
            }
            objects.add(profile);
        }
        return objects;
    }

    public void lookupFilterExecute(String apiname, String objname) {
        System.out.println("查找筛选条件迁移开始 =================== ");
        JSONObject lookupFilterJson = new JSONObject();
        String object_sql = "select id from tp_sys_object where schemetable_name ='" + objname + "'";
        List<CCObject> object_list = mcs.cqlQuery("tp_sys_object", object_sql);
        String object_id = "";
        if (!object_list.isEmpty()) {
            object_id = object_list.get(0).get("id") == null ? "" : object_list.get(0).get("id").toString();
        }

        String objsql = "select id from tp_sys_schemetable " +
                "where schemefield_name='" + apiname + "' and " +
                "(select schemetable_name from tp_sys_object where id=tp_sys_schemetable.schemetable_id)='" + objname + "'";
        List<CCObject> objList = cs.cqlQuery("TP_SYS_SCHEMETABLE", objsql);
        List<CCObject> newobjList = mcs.cqlQuery("TP_SYS_SCHEMETABLE", objsql);
        if (objList.isEmpty()) {
            return;
        }
        String apiid = objList.get(0).get("id") == null ? "" : objList.get(0).get("id").toString();
        if (objList.isEmpty()) {
            return;
        }
        String newapiid = newobjList.get(0).get("id") == null ? "" : newobjList.get(0).get("id").toString();
        JSONObject fieldObj = new JSONObject();
        fieldObj.put("id", newapiid);
        String queryLookupFilterSql = "select ( select schemetable_name from tp_sys_object where id = tp_sys_lookup_filter_condition.left_object ) left_object,( select schemetable_name from tp_sys_object where id = tp_sys_lookup_filter_condition.right_object ) right_object,( select schemefield_name from tp_sys_schemetable where id = tp_sys_lookup_filter_condition.left_field ) left_field,( select schemefield_name from tp_sys_schemetable where id = tp_sys_lookup_filter_condition.right_field ) right_field, operator op, value_field valfld, value val, filterlogic from tp_sys_lookup_filter_condition where PARENTID ='" + apiid + "'";
        List<CCObject> LookupFilterList = cs.cqlQuery("tp_sys_lookup_filter_condition", queryLookupFilterSql);
        if (LookupFilterList.isEmpty()) {
            return;
        }
        String filterlogic = LookupFilterList.get(0).get("filterlogic") == null ? "" : LookupFilterList.get(0).get("filterlogic").toString();
        fieldObj.put("filterLogic", filterlogic);
        fieldObj.put("isenableFilter", "true");
        lookupFilterJson.put("fieldObj", fieldObj);
        lookupFilterJson.put("isCondition", "true");
        JSONObject conditionVals = new JSONObject();
        JSONArray data = new JSONArray();
        for (CCObject row : LookupFilterList) {
            JSONObject par = new JSONObject();
            String left_object = row.get("left_object") == null ? "" : row.get("left_object").toString();
            String left_object_sql = "select id from tp_sys_object where schemetable_name ='" + left_object + "'";
            List<CCObject> left_object_list = mcs.cqlQuery("tp_sys_object", left_object_sql);
            String left_object_id = "";
            if (!left_object_list.isEmpty()) {
                left_object_id = left_object_list.get(0).get("id") == null ? "" : left_object_list.get(0).get("id").toString();
            }
            String left_field = row.get("left_field") == null ? "" : row.get("left_field").toString();
            String left_field_sql = "select id from tp_sys_schemetable where schemefield_name='" + left_field + "'  and schemetable_id='" + left_object_id + "'";
            List<CCObject> left_field_list = mcs.cqlQuery("tp_sys_schemetable", left_field_sql);
            String left_field_id = "";
            if (!left_field_list.isEmpty()) {
                left_field_id = left_field_list.get(0).get("id") == null ? "" : left_field_list.get(0).get("id").toString();
            }

            String right_object = row.get("right_object") == null ? "" : row.get("right_object").toString();
            String right_object_sql = "select id from tp_sys_object where schemetable_name ='" + right_object + "'";
            List<CCObject> right_object_list = mcs.cqlQuery("tp_sys_object", right_object_sql);
            String right_object_id = "";
            if (!right_object_list.isEmpty()) {
                right_object_id = right_object_list.get(0).get("id") == null ? "" : right_object_list.get(0).get("id").toString();
            }
            String right_field = row.get("right_field") == null ? "" : row.get("right_field").toString();
            String right_field_sql = "select id from tp_sys_schemetable where schemefield_name='" + right_field + "'  and schemetable_id='" + right_object_id + "'";
            List<CCObject> right_field_list = mcs.cqlQuery("tp_sys_schemetable", right_field_sql);
            String right_field_id = "";
            if (!right_field_list.isEmpty()) {
                right_field_id = right_field_list.get(0).get("id") == null ? "" : right_field_list.get(0).get("id").toString();
            }
            String leftvalue = "";
            if (!left_field_id.equals("") && !left_object_id.equals("")) {
                leftvalue = left_object_id + "-" + left_field_id;
            }
            String rightvalue = "";
            if (!right_field_id.equals("") && !right_object_id.equals("")) {
                rightvalue = right_object_id + "-" + right_field_id;
            }
            par.put("leftvalue", leftvalue);
            par.put("op", row.get("op") == null ? "" : row.get("op").toString());
            par.put("valfld", row.get("valfld") == null ? "" : row.get("valfld").toString());
            par.put("val", row.get("val") == null ? "" : row.get("val").toString());
            par.put("rightvalue", rightvalue);
            data.add(par);
        }
        conditionVals.put("data", data.toString());
        conditionVals.put("filter", filterlogic);
        conditionVals.put("mainObjId", object_id);
        conditionVals.put("relatedObjId", "");
        lookupFilterJson.put("conditionVals", conditionVals);
        String s = saveFieldLookupFilter(lookupFilterJson);
        System.out.println("lookupFilterJson = " + lookupFilterJson);
        System.out.println("查找筛选条件迁移结束 =================== " + s);
    }

    public String saveFieldLookupFilter(JSONObject parStr) {
        String errmsg = "";
        //  保存接口URL
        String Purl = mcs.gatewayUrl() + "/setup/api/fieldSetup/saveFieldLookupFilter";
        System.out.println("Purl = " + Purl);
        // 发送POST请求并获取响应
        String ObjStr = mcs.CCPost(Purl, parStr.toString());
        // 打印响应结果，便于调试
        System.out.println("ObjStr = " + ObjStr);
        // 解析响应的JSON对象
        JSONObject obj = JSONObject.parseObject(ObjStr);

        // 根据响应结果判断操作是否成功
        if (StringUtil.str2b(obj.getString("result"))) {
//            System.out.println("操作成功！");
            errmsg = "操作成功！";
        } else {
            // 获取并打印失败原因
            String returnInfo = StringUtil.str(obj.getString("returnInfo"));
//            System.out.println("操作失败-returnInfo = " + returnInfo);
            errmsg = "操作失败！" + returnInfo;
        }
        return errmsg;
    }

    public void buttonExecute(String objname) {
        String objsql = "select id from TP_SYS_OBJECT where schemetable_name = '" + objname + "'";
        // 执行查询并获取结果列表
        List<CCObject> dlist = mcs.cqlQuery("TP_SYS_OBJECT", objsql);
        // 如果查询结果不为空，则遍历结果列表，提取并存储对象名称与ID的对应关系
        String tableid = "";
        if (dlist.size() > 0) {
            tableid = StringUtil.str(dlist.get(0).get("id"));
        }
        String queryButtonSql = "SELECT label,name,btn_type,event,behavior,menubar,function_code,remark,mobileurl,h5function_code,category,custompage_id,iscustom,visible" +
                " FROM TP_SYS_BUTTON where category='CustomButton'  and" +
                "  (select schemetable_name from TP_SYS_OBJECT where id=TP_SYS_BUTTON.obj_id)='" + objname + "' ";
        List<CCObject> buttoncco = cs.cqlQuery("TP_SYS_BUTTON", queryButtonSql);
        if (!buttoncco.isEmpty()) {
            for (CCObject row : buttoncco) {
                JSONObject buttonObj = new JSONObject();
                JSONObject tpSysButtonVO = new JSONObject();
                //拼接参数
                String label = row.get("label") == null ? "" : row.get("label").toString();
                String name = row.get("name") == null ? "" : row.get("name").toString();
                String btnType = row.get("btn_type") == null ? "" : row.get("btn_type").toString();
                String event = row.get("event") == null ? "" : row.get("event").toString();
                String behavior = row.get("behavior") == null ? "" : row.get("behavior").toString();
                String functionCode = row.get("function_code") == null ? "" : row.get("function_code").toString();
                String remark = row.get("remark") == null ? "" : row.get("remark").toString();
                String mobileurl = row.get("mobileurl") == null ? "" : row.get("mobileurl").toString();
                String h5FunctionCode = row.get("h5function_code") == null ? "" : row.get("h5function_code").toString();
                String category = row.get("category") == null ? "" : row.get("category").toString();
                String custompageId = row.get("custompage_id") == null ? "" : row.get("custompage_id").toString();
                String iscustom = row.get("iscustom") == null ? "" : row.get("iscustom").toString();
                String visible = row.get("visible") == null ? "" : row.get("visible").toString();
                tpSysButtonVO.put("label", label);
                tpSysButtonVO.put("name", name);
                tpSysButtonVO.put("btnType", btnType);
                tpSysButtonVO.put("event", event);
                tpSysButtonVO.put("behavior", behavior);
                tpSysButtonVO.put("menubar", true);
                tpSysButtonVO.put("functionCode", functionCode);
                tpSysButtonVO.put("remark", remark);
                tpSysButtonVO.put("mobileurl", mobileurl);
                tpSysButtonVO.put("h5FunctionCode", h5FunctionCode);
                tpSysButtonVO.put("category", category);
                tpSysButtonVO.put("custompageId", custompageId);
                tpSysButtonVO.put("iscustom", iscustom);
                tpSysButtonVO.put("visible", visible);
                buttonObj.put("tpSysButtonVO", tpSysButtonVO);
                buttonObj.put("objid", tableid);
                System.out.println("buttonObj = " + buttonObj);
                String mag = saveButton(buttonObj);
                System.out.println("按钮" + name + "迁移完成，mag = " + mag);
            }
        }

    }


    public String saveButton(JSONObject parStr) {
        String errmsg = "";
        //  保存接口URL
        String Purl = mcs.gatewayUrl() + "/setup/api/buttonlink/saveButton";
        // 发送POST请求并获取响应
        String ObjStr = mcs.CCPost(Purl, parStr.toString());

        // 打印响应结果，便于调试
        System.out.println("ObjStr = " + ObjStr);
        // 解析响应的JSON对象
        JSONObject obj = JSONObject.parseObject(ObjStr);


        // 根据响应结果判断操作是否成功
        if (StringUtil.str2b(obj.getString("result"))) {
//            System.out.println("操作成功！");
            errmsg = "操作成功！";
        } else {
            // 获取并打印失败原因
            String returnInfo = StringUtil.str(obj.getString("returnInfo"));
//            System.out.println("操作失败-returnInfo = " + returnInfo);
            errmsg = "操作失败！" + returnInfo;
        }
        return errmsg;
    }

}
